package com.geaosu.niubiplus_java.utils.ImageLoader;

import android.graphics.Bitmap;
import android.util.LruCache;

/**
 * 缓存器 - 内存缓存
 * 特点：速度快
 * 缺点：
 * 1.容量有限，不适合图片太多的业务；
 * 2.一次性缓存，app一旦关闭，缓存内容就会丢失；
 */
public class ImageCache {
    private static ImageCache mInstance;
    private LruCache<String, Bitmap> mImageCatche;

    private ImageCache() {
        long appMaxMemory = Runtime.getRuntime().maxMemory() / 1024;
        int imageCacheMaxSize = (int) (appMaxMemory / 4);
        mImageCatche = new LruCache<String, Bitmap>(imageCacheMaxSize) {
            @Override
            protected int sizeOf(String url, Bitmap bitmap) {
                int imgSize = bitmap.getRowBytes() * bitmap.getHeight() / 1024;
                return imgSize;
            }
        };
    }

    public static ImageCache getDefault() {
        if (mInstance == null) {
            mInstance = new ImageCache();
        }
        return mInstance;
    }


    /**
     * 存储
     */
    public void put(String url, Bitmap bitmap) {
        mImageCatche.put(url, bitmap);
    }

    /**
     * 获取
     */
    public Bitmap get(String url) {
        Bitmap bitmap = mImageCatche.get(url);
        return bitmap;
    }
}
